<template>
  <div>
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="changeTab">
      <el-menu-item index="my" v-if="myPurchaseTargetGoods">我的</el-menu-item>
      <el-menu-item index="all" v-if="allPurchaseTargetGoods">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
        <el-form-item label="销售日期：">
          <el-date-picker
            v-model="listQuery.targetDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="品类：">
          <el-select
            filterable
            clearable
            v-model="listQuery.goodsName">
            <el-option
              v-for="item in options2"
              :key="item.goodsName"
              :label="item.goodsName"
              :value="item.goodsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.goodsKingId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购员：" v-if="listQuery.tab != 'my'">
          <el-select size="mini" v-model="listQuery.purchaseUserId" clearable  placeholder="请选择人员" >
            <el-option v-for="item in userOptionList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度：">
          <el-select v-model="listQuery.urgencyType"  placeholder="请选择" clearable>
            <el-option key="1" label="紧急" value="紧急"></el-option>
            <el-option key="0" label="正常" value="正常"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            v-if="listQuery.tab == 'my'"
            @click="showPop('add','')"
            type="primary">
            新增采购货源
          </el-button>
          <el-button
            v-if="listQuery.tab == 'my'"
            @click="showPopMore('add','')"
            type="success">
            批量新增货源
          </el-button>
          <el-button
            v-if="listQuery.tab == 'my'"
            @click="showPopMore('copy')"
            type="success">
            批量复制货源
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        ref="multipleTable"
        row-key="tpdId"
        @selection-change="handleSelectionChange"
        :row-style="setRowStyle"
        v-loading="listLoading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column type="selection" :reserve-selection="true" width="60" align="center"></el-table-column>
        <el-table-column
          label="品类"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column
          label="牌号"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsNum}}
          </template>
        </el-table-column>
        <el-table-column
          label="参考价格"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsPrice}}
          </template>
        </el-table-column>
        <el-table-column
          label="紧急程度"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.urgencyType}}
          </template>
        </el-table-column>
        <el-table-column
          label="交期"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.sendDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="整车/散货"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.isFullCar}}
          </template>
        </el-table-column>
        <el-table-column
          label="提货地址"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.sendArea}}
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
        <el-table-column
          label="销售日期"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.targetDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="负责采购"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.purchaseUserName}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" v-if="listQuery.tab=='my'"  @click="showPop('copy',scope.row)">复制</el-button>
            <el-button type="text" v-if="scope.row.targetDateTime > nowDate && listQuery.tab=='my'" @click="showPop('edit',scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--复制/更新货源-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="dialogVisible"
      width="800px">
      <el-form :model="form" size="mini" label-width="100px" ref="form" :rules="rules">
        <el-row>
           <el-col :span="12">
             <el-form-item label="销售日期：" prop="targetDate">
               <el-date-picker
                 value-format="yyyy-MM-dd"
                 :picker-options="pickerOptions"
                 v-model="form.targetDate"
                 type="date"
                 placeholder="选择日期">
               </el-date-picker>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="交货日期：" prop="sendDate">
               <el-date-picker
                 value-format="yyyy-MM-dd"
                 :picker-options="pickerOptions"
                 v-model="form.sendDate"
                 type="date"
                 placeholder="选择日期">
               </el-date-picker>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="品类牌号：" prop="goodsKingId">
               <el-select v-model="form.goodsKingId" filterable placeholder="请选择" clearable style="width:220px">
                 <el-option
                   v-for="item in goodsList2"
                   :key="item.kingId"
                   :label="item.goodsSn"
                   :value="item.kingId">
                 </el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="数量：" prop="goodsNum">
               <el-input v-model="form.goodsNum" style="width:220px" type="number"></el-input>
             </el-form-item>
           </el-col>
          <el-col :span="12">
            <el-form-item label="参考价格：" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" style="width:220px" type="number"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="12">
             <el-form-item label="紧急程度：" prop="urgencyType">
               <el-radio-group v-model="form.urgencyType">
                 <el-radio label="紧急">紧急</el-radio>
                 <el-radio label="正常">正常</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="运输模式‌：" prop="isFullCar">
               <el-radio-group v-model="form.isFullCar">
                 <el-radio label="整车">整车</el-radio>
                 <el-radio label="散货">散货</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="提货地址：" prop="sendAreaId">
               <el-cascader
                 filterable
                 clearable
                 v-model="form.sendAreaId"
                 :props="{ value: 'areaId',label:'areaName',children:'children',emitPath:false}"
                 :options="options"
               >
               </el-cascader>
             </el-form-item>
           </el-col>
          <el-col :span="12">
            <el-form-item label="备注：" >
              <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!--批量复制/新增货源-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :visible.sync="dialogVisibleMore"
      width="1000px">
      <el-form :model="moreform" size="mini" label-width="100px" ref="moreform" :rules="rules">
        <el-table
          :data="moreform.targetData"
          border
          size="mini"
          :header-cell-style="{ background: '#f8f8f9', color: '#80878f' }"
          style="width: 100%;"
          ref="table"
        >
          <el-table-column align="center" label="销售日期" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.targetDate`"
                            :rules="rules.targetDate"
                            label-width="0px">
                <el-date-picker
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  v-model="scope.row.targetDate"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="交货日期" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.sendDate`"
                            :rules="rules.sendDate"
                            label-width="0px">
                <el-date-picker
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  v-model="scope.row.sendDate"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="品类牌号" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.goodsKingId`"
                            :rules="rules.goodsKingId"
                            label-width="0px">
                <el-select v-model="scope.row.goodsKingId" filterable placeholder="请选择" clearable style="width:100%">
                  <el-option
                    v-for="item in goodsList2"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="数量" width="120">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.goodsNum`"
                            :rules="rules.goodsNum"
                            label-width="0px">
                <el-input v-model="scope.row.goodsNum" style="width:100px" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" label="参考价格" width="120">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.goodsPrice`"
                            :rules="rules.goodsPrice"
                            label-width="0px">
                <el-input v-model="scope.row.goodsPrice" style="width:100px" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="紧急程度" width="180">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.urgencyType`"
                            :rules="rules.urgencyType"
                            label-width="0px">
                <el-radio-group v-model="scope.row.urgencyType">
                  <el-radio label="紧急">紧急</el-radio>
                  <el-radio label="正常">正常</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="运输模式‌" width="180">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.isFullCar`"
                            :rules="rules.isFullCar"
                            label-width="0px">
                <el-radio-group v-model="scope.row.isFullCar">
                  <el-radio label="整车">整车</el-radio>
                  <el-radio label="散货">散货</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="提货地址" width="200">
            <template slot-scope="scope">
              <el-form-item :prop="`targetData.${scope.$index}.sendAreaId`"
                            :rules="rules.sendAreaId"
                            label-width="0px">
                <el-cascader
                  filterable
                  clearable
                  v-model="scope.row.sendAreaId"
                  :props="{ value: 'areaId',label:'areaName',children:'children',emitPath:false}"
                  :options="options"
                >
                </el-cascader>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column align="center" label="备注" width="200">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-input v-model="scope.row.remark"></el-input>
              </el-form-item>
            </template>
          </el-table-column>


          <el-table-column
            label="操作"
            width="100"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                :disabled="moreform.targetData.length<=1"
                type="text"
                size="mini"
                @click="delItem(scope.$index)"
              >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-button  @click="addItem" size="small" style="margin-top: 10px">添加货源</el-button>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getOrderUsersList,orderGoodsList,getGoodsClassList} from '@/api/partner'
import {goodsList} from '@/api/company'
import { purchaseTargetSet,purchaseTargetList } from '@/api/allInLine/goods.js'
import {getAreaList} from '@/api/allInLine/inquiry'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery={
  "goodsKingId" : '',
  "targetDate" : [],
  "purchaseUserId" : '',
  "urgencyType" : "",
  "tab" : "",
  goodsName:"",
  "pageNum" : 1,
  "pageSize" : 10
};
let today = new Date();  // 获取当前日期
let tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);

const defaultForm={
  "tpdId" : '',
  "targetDate" : formatDate(tomorrow, 'yyyy-MM-dd'),
  "goodsKingId" : '',
  "goodsNum" : '',
  "sendDate" : "",
  "isFullCar" : "",
  "sendAreaId" : '',
  "remark" : "",
  "urgencyType" : "",
  goodsPrice:''
}

export default {
  name: "sourceGoodsSetting",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      loading:false,
      count:0,
      activeName:'first',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      userOptionList:[],
      dialogVisible:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      btnLoading:false,
      goodsList:[],

      rules:{
        targetDate:[{required: true, message: '此项必填', trigger: 'change'},],
        goodsKingId:[{required: true, message: '此项必填', trigger: 'change'},],
        goodsNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        sendDate:[{required: true, message: '此项必填', trigger: 'change'},],
        isFullCar:[{required: true, message: '此项必填', trigger: 'change'},],
        sendAreaId:[{required: true, message: '此项必填', trigger: 'change'},],
        urgencyType:[{required: true, message: '此项必填', trigger: 'change'},],
        goodsPrice:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      title:'',

      logs:[],
      dialogVisible2:false,
      options:[],
      goodsList2:[],
      options2:[],

      moreform: {targetData:[]},
      btnLoading2:false,
      dialogVisibleMore:false,
      title2:'',
      selectList:[]

    }
  },
  props: {

    nowDate:{
      type: Number,
      default: () => parseInt(Date.parse(new Date())/1000)
    },
    startDate:{
      type: String,
      default: () => ''
    },
    endDate:{
      type: String,
      default: () => ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
    myPurchaseTargetGoods(){
      if(this.roles.indexOf("myPurchaseTargetGoods") != -1){
        return true
      }else{
        return false
      }
    },
    allPurchaseTargetGoods(){
      if(this.roles.indexOf("allPurchaseTargetGoods") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    var today = new Date();  // 获取当前日期
    var tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    this.listQuery.targetDate = [formatDate(tomorrow, 'yyyy-MM-dd'),formatDate(tomorrow, 'yyyy-MM-dd')];
    if(this.myPurchaseTargetGoods) {
      this.listQuery.tab = 'my'
    }else if(this.allPurchaseTargetGoods){
      this.listQuery.tab = 'all'
    }
    this.getList();
    orderGoodsList().then((res)=>{
      this.goodsList = res.list
    })
    orderGoodsList({chargeUserId:this.userId}).then((res)=>{
      this.goodsList2 = res.list
    })
    this.getUserList();
    this.getAddressListData();
    this.remoteMethod3();
  },
  filters: {



  },
  methods:{

    handleSelectionChange(val){
      this.selectList = JSON.parse(JSON.stringify(val));
    },
    addItem(){
      this.moreform.targetData.push(JSON.parse(JSON.stringify(defaultForm)))
    },
    delItem(index){
      this.moreform.targetData.splice(index,1);
    },
    showPopMore(type){
      this.moreform.targetData = []
      if(type == 'add'){
        this.moreform.targetData.push(JSON.parse(JSON.stringify(defaultForm)))
        this.title2 = '批量新增货源'
      }else if(type == 'copy'){
        this.title2 = '批量复制货源'
        if(this.selectList.length == 0){
          this.$message.warning('请选择要复制的货源')
          return false
        }
        this.selectList.forEach((el)=>{
          let c = {}
          for(let key  in defaultForm){
            c[key] = el[key] ? el[key] : ''
          }
          let today = new Date();  // 获取当前日期
          let tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
          c.targetDate = formatDate(tomorrow, 'yyyy-MM-dd');
          c.sendDate = '';
          c.tpdId = '';
          this.moreform.targetData.push(c);
        });
      }
      this.dialogVisibleMore = true;
    },

    handleConfirm2(){
      this.$refs.moreform.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.moreform));
          purchaseTargetSet(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.getList();
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },
    handleClose2(){
      this.dialogVisibleMore = false
      this.$refs.multipleTable.clearSelection();
      this.selectList = []
    },
    //获取品类列表
    remoteMethod3() {
      getGoodsClassList().then((res)=>{
        this.options2 = res;
      }).catch(()=>{
      });
    },
    setRowStyle({row, rowIndex}) {
      if (row.urgencyType === '紧急') {
        return { 'background-color': '#f9ebeb' };
      } else {
        return {}; // 默认样式或留空返回空对象以使用默认样式
      }
    },
    getAddressListData(){
      getAreaList().then((res)=>{
        this.options = res;
      })
    },
    changeTab(key){
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
      this.listQuery.tab = key;
      this.listQuery.targetDate = [this.startDate,this.endDate];
      this.handleSearchList()
    },
    showLog(item){
      this.dialogVisible2 = true;
      orderLogs({orderId:item.orderId}).then((res)=>{
        this.logs = res
      })
    },
    getUserList(){
      getOrderUsersList({departmentId:3,status:1}).then((res)=>{
        this.userOptionList = res;
      })
    },

    showPop(type,item){
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      var today = new Date();  // 获取当前日期
      var tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      if(type == 'edit'){
        this.title = '编辑货源'
        for(let key  in defaultForm){
          this.form[key] = item[key] ? item[key] : ''
        }
      }else if(type == 'copy'){
        this.title = '复制货源'
        for(let key  in defaultForm){
          this.form[key] = item[key] ? item[key] : ''
        }
        this.form.targetDate = formatDate(tomorrow, 'yyyy-MM-dd');
        this.form.sendDate = '';
        this.form.tpdId = ''
      }else{
        this.title = '新增货源'
        this.form.targetDate = formatDate(tomorrow, 'yyyy-MM-dd');
      }
    },

    handleClose(){
      this.dialogVisible = false;
    },
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          purchaseTargetSet({targetData:[data]}).then((res)=>{
            this.btnLoading = false;
            this.handleClose();
            this.getList();
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let pa = JSON.parse(JSON.stringify(this.listQuery))
      purchaseTargetList(pa).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },


  },
}
</script>

<style scoped lang="scss">

</style>
